<!-- 搜索表单 -->
<div class="layui-form"
    style="margin-bottom: 15px; padding: 15px; background-color: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); border: 1px solid #e6e6e6;">
    <div class="layui-form-item" style="margin-bottom: 0;">
        <div class="layui-input-inline" style="width: 320px;">
            <input type="text" id="searchKeyword" placeholder="请输入订单ID、用户名或商品名称" class="layui-input"
                style="border-radius: 4px; border-color: #dcdfe6; transition: all 0.3s;">
        </div>
        <div class="layui-input-inline" style="width: auto;">
            <button class="layui-btn layui-btn-normal" id="searchBtn"
                style="border-radius: 4px; padding: 0 20px;">搜索</button>
        </div>
        <div class="layui-input-inline" style="width: auto;">
            <button class="layui-btn layui-btn-primary" id="resetBtn"
                style="border-radius: 4px; padding: 0 20px;">重置</button>
        </div>
    </div>
</div>

<script>
    /**
     * 搜索订单功能初始化
     * @param {Object} $ - jQuery 实例
     * @param {Object} orderTable - 订单表格实例
     * @param {Object} form - layui form 实例
     */
    function searchOrderInit($, orderTable, form) {
        // 防抖函数
        function debounce(fn, delay) {
            let timer = null;
            return function () {
                const context = this;
                const args = arguments;
                clearTimeout(timer);
                timer = setTimeout(() => {
                    fn.apply(context, args);
                }, delay);
            };
        }

        // 搜索处理函数
        function doSearch() {
            var keyword = $('#searchKeyword').val().trim();

            // 空输入框错误提示
            if (!keyword) {
                layer.msg('请输入搜索关键词', {
                    icon: 2,
                    time: 2000
                });
                return;
            }

            // 重新加载表格数据
            orderTable.reload({
                where: {
                    "keyword": keyword,
                    "page": 1,
                    "page_size": 10,
                    "uid": userInfo.uid
                },
                page: {
                    curr: 1 // 重新从第1页开始
                }
            });
        }

        // 重置后直接重新加载表格
        function resetAndReload() {
            $('#searchKeyword').val('');
            form.render();

            // 直接重新加载表格数据
            orderTable.reload({
                where: {
                    "keyword": '',
                    "page": 1,
                    "page_size": 10,
                    "uid": userInfo.uid
                },
                page: {
                    curr: 1 // 重新从第1页开始
                }
            });
        }

        // 创建防抖处理的搜索函数
        const debouncedSearch = debounce(doSearch, 300);

        // 绑定搜索按钮点击事件
        $('#searchBtn').click(function () {
            doSearch();
        });

        // 绑定重置按钮点击事件
        $('#resetBtn').click(function () {
            resetAndReload();
        });

        // 绑定回车键搜索
        $('#searchKeyword').on('keydown', function (e) {
            if (e.keyCode === 13) {
                doSearch();
            }
        });

        // 绑定输入框变化事件（带防抖）
        $('#searchKeyword').on('input', debouncedSearch);
    }
</script>

<script>
    /**
     * 订单操作栏初始化
     * @param {Object} table - layui table 实例
     * @param {Object} form - layui form 实例
     * @param {Object} layer - layui layer 实例
     * @param {Object} $ - jQuery 实例
     */
    function orderBarInit(table, form, layer, $) {
        // 监听表格行工具事件
        table.on('tool(orderTable)', function (obj) {
            var data = obj.data; // 获得当前行数据
            var layEvent = obj.event; // 获得 lay-event 对应的值

            if (layEvent === 'update') {
                // 更新订单
                updateOrderFunc(data, table, form, layer, $);
            } else if (layEvent === 'delete') {
                // 删除订单
                deleteOrderFunc(data, table, layer);
            }
        });
    }

    /**
     * 更新订单功能函数
     * @param {Object} data - 当前订单数据
     * @param {Object} table - layui table 实例
     * @param {Object} form - layui form 实例
     * @param {Object} layer - layui layer 实例
     * @param {Object} $ - jQuery 实例
     */
    function updateOrderFunc(data, table, form, layer, $) {
        // 创建表单HTML
        var formHtml = `
        <form class="layui-form" style="padding: 20px;" lay-filter="updateOrderForm">
            <div class="layui-form-item">
                <label class="layui-form-label">订单ID</label>
                <div class="layui-input-block">
                    <input type="text" name="oid" value="${data.oid}" readonly class="layui-input layui-disabled">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="username" value="${data.username || ''}" readonly class="layui-input layui-disabled">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">商品名称</label>
                <div class="layui-input-block">
                    <input type="text" name="product_name" value="${data.product_name || ''}" readonly class="layui-input layui-disabled">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">消耗积分</label>
                <div class="layui-input-block">
                    <input type="number" name="points" value="${data.points || 0}" readonly class="layui-input layui-disabled">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">订单状态</label>
                <div class="layui-input-block">
                    <select name="status" lay-verify="required" class="layui-input">
                            <option value="1" ${data.status == 1 ? 'selected' : ''}>待支付</option>
                            <option value="2" ${data.status == 2 ? 'selected' : ''}>已支付</option>
                            <option value="3" ${data.status == 3 ? 'selected' : ''}>已发货</option>
                            <option value="4" ${data.status == 4 ? 'selected' : ''}>已完成</option>
                            <option value="5" ${data.status == 5 ? 'selected' : ''}>已取消</option>
                        </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">创建时间</label>
                <div class="layui-input-block">
                    <input type="text" name="create_time" value="${data.create_time || ''}" readonly class="layui-input layui-disabled">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">更新时间</label>
                <div class="layui-input-block">
                    <input type="text" name="update_time" value="${data.update_time || ''}" readonly class="layui-input layui-disabled">
                </div>
            </div>
        </form>
        `;

        // 打开弹窗
        var index = layer.open({
            type: 1,
            title: '更新订单',
            content: formHtml,
            area: ['600px', 'auto'],
            btn: ['提交', '取消'],
            success: function (layero) {
                // 刷新表单渲染
                form.render();
            },
            yes: function (index) {
                // 获取表单数据
                var formData = form.val('updateOrderForm');

                // 表单验证
                var isError = false;
                if (!formData.oid) {
                    layer.msg('订单ID不能为空', { icon: 5 });
                    isError = true;
                } else if (!formData.status || !['1', '2', '3', '4', '5'].includes(formData.status)) {
                    layer.msg('请选择有效的订单状态', { icon: 5 });
                    isError = true;
                }

                if (isError) {
                    return;
                }

                // 删除积分、创建时间、更新时间、product_name、username字段
                delete formData.points;
                delete formData.create_time;
                delete formData.update_time;
                delete formData.product_name;
                delete formData.username;

                // 发送请求更新订单
                axios({
                    url: '/api/order/update_order/',
                    method: 'POST',
                    data: formData,
                }).then(res => {
                    res = res.data;
                    if (res.code === 0) {
                        layer.msg('订单更新成功', { icon: 6 });
                        layer.close(index);
                        // 刷新表格
                        table.reload('orderTable');
                    } else {
                        layer.msg(res.message || '更新失败', { icon: 5 });
                    }
                }).catch(() => {
                    layer.msg('网络错误，请重试', { icon: 5 });
                })
            }
        });
    }

    /**
     * 删除订单功能函数
     * @param {Object} data - 当前订单数据
     * @param {Object} table - layui table 实例
     * @param {Object} layer - layui layer 实例
     */
    function deleteOrderFunc(data, table, layer) {
        // 弹出确认框
        layer.confirm('确定要删除该订单吗？删除后数据将无法恢复', {
            btn: ['确定', '取消']
        }, function (index) {
            // 发送请求删除订单
            axios({
                url: '/api/order/delete_order/',
                method: 'POST',
                data: {
                    oid: data.oid
                },
            }).then(res => {
                res = res.data;
                if (res.code === 0) {
                    layer.msg('订单删除成功', { icon: 6 });
                    // 刷新表格
                    table.reload('orderTable');
                } else {
                    layer.msg(res.message || '删除失败', { icon: 5 });
                }
            }).catch(() => {
                layer.msg('网络错误，请重试', { icon: 5 });
            }).finally(() => {
                layer.close(index);
            })
        });
    }
</script>